import 'package:flutter/material.dart';
import 'package:pp_uikit/theme/pp_default_theme.dart';

/// 用于分割页面组件元素的横向分割线
/// 支持自定义颜色、左右间距、和高度
///
/// 系统提供的[Divider]组件，当设置的高度过大时，会出现中间一条线，
///
/// ```dart
///   PPLine()
///
///   PPLine(
///      leftInset: 20,
///   )
///
/// ```
///
/// 相关分割线如下:
///
// ignore: must_be_immutable
class PPLine extends StatelessWidget {
  /// 分割线的或者分割条的颜色
  final Color? color;

  /// 分割线的或者分割条的高度 默认0.5
  final double height;

  /// 左边缩进距离
  final double leftInset;

  /// 右边缩进距离
  final double rightInset;

  /// top缩进距离
  final double topInset;

  /// bottom缩进距离
  final double bottomInset;

  /// 是否为虚线
  final bool isDashed;

  const PPLine({
    Key? key,
    this.color,
    this.height = 1,
    this.leftInset = 0,
    this.rightInset = 0,
    this.topInset = 0,
    this.bottomInset = 0,
    this.isDashed = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var width = MediaQuery.maybeOf(context)?.size.width ?? 0;
    width = width - leftInset - rightInset;
    if (isDashed) {
      return Padding(
        padding: EdgeInsets.only(
          left: leftInset,
          right: rightInset,
          top: topInset,
          bottom: bottomInset,
        ),
        child: CustomPaint(
          painter: _DashedLinePainter(color ?? PPDefaultTheme.lineColor),
          size: Size(width, height),
        ),
      );
    }
    return Padding(
      padding: EdgeInsets.only(
        left: leftInset,
        right: rightInset,
        top: topInset,
        bottom: bottomInset,
      ),
      child: Divider(
        thickness: height,
        height: height,
        color: color ?? PPDefaultTheme.instance.backgroundColor,
      ),
    );
  }
}

/// 绘制虚线
class _DashedLinePainter extends CustomPainter {
  final Color color;

  _DashedLinePainter(this.color);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = 1.0
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    const dashWidth = 2;
    const dashSpace = 4;
    double startX = 0.0;
    while (startX < size.width) {
      canvas.drawLine(Offset(startX, 0), Offset(startX + dashWidth, 0), paint);
      startX += dashWidth + dashSpace;
    }
  }

  @override
  bool shouldRepaint(_DashedLinePainter oldDelegate) {
    return oldDelegate.color != color;
  }
}
